layui.use(['jquery', 'table', 'layer', 'laydate', 'form', 'upload'], function () {
    var $ = layui.jquery;
    var table = layui.table;
    var layer = layui.layer;
    var laydate = layui.laydate;
    var form = layui.form;
    var upload = layui.upload;

    laydate.render({
        elem: "#registerDate",
        type: "date",
        tigger: "click"
    });

    /* 树开始 */
    var zTree;
    var demoIframe;

    var setting = {
        view: {
            dblClickExpand: false
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "id",   //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                enable: true,
                name: "deptName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            //onRightClick: onRightClick,
            // beforeRemove: beforeRemove,//点击删除时触发，用来提示用户是否确定删除（可以根据返回值 true|false 确定是否可以删除）
            // beforeEditName: beforeEditName,//点击编辑时触发，用来判断该节点是否能编辑
            //beforeRename: beforeRename,//编辑结束时触发，用来验证输入的数据是否符合要求(也是根据返回值 true|false 确定是否可以编辑完成)
            // beforeDrag: beforeDrag,//用户禁止拖动节点
            onClick: chooseNode,
        }
    };
    $(document).ready(function () {
        $.ajax({
            type: "post",
            dataType: "json",
            url: "/jurisdiction/getJsDeptName",
            success: function (data) {
                zTree = $.fn.zTree.init($("#tree"), setting, data.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        });
        demoIframe = $("#rMenu");

    });
    /* 树结束 */

    /* 表格渲染开始 */
    var people = table.render({
        elem: "#root",
        url: "/jurisdiction/getJsUser?account=" + '' + "&trueName=" + '' + "&deptName=" + '' + "&registerDate=" + '',
        toolbar: "#toptool",
        page: true,
        limit: 5,
        limits: [5, 10, 15, 20],
        size: 'lg',
        cols: [
            [
                {type: "checkbox", align: "center"},
                {type: "numbers", title: "序号", align: "center"},
                {field: "trueName", title: "用户姓名", align: "center"},
                {
                    field: "acatarUrl", title: "用户头像", align: "center", templet: function (data) {
                        return '<img src=' +"http://"+ data.acatarUrl + ' />';
                    }
                },
                {field: "sex", title: "性别", align: "center"},
                {field: "account", title: "用户账号", align: "center"},
                {field: "deptName", title: "所属部门", align: "center"},
                {
                    field: "enabled", title: "是否启用", align: "center", templet: function (data) {
                        if (data.enabled == 1) {
                            var radio1 = '<a href="javascript:updateStatus(' + data.userId + ',' + data.status + ',' + data.enabled + ');"><input class="layui-input swi" type="checkbox" name="enable" lay-skin="switch" lay-text="启用|停用" lay-filter="switchTest" value="' + data.enable + '" checked></a>';
                        } else {
                            var radio1 = '<a href="javascript:updateStatus(' + data.userId + ',' + data.status + ',' + data.enabled + ');"><input class="layui-input swi" type="checkbox" name="enable" lay-skin="switch" lay-text="启用|停用" lay-filter="switchTest" value="' + data.enable + '"></a>';
                        }
                        return radio1;
                    }
                },
                {
                    field: "status", title: "账号状态", align: "center", templet: function (data) {
                        if (data.status == 1) {
                            var radio2 = '<a href="javascript:updateStatus(' + data.userId + ',' + data.status + ',' + data.enabled + ');"><input class="layui-input swi" type="checkbox" name="status" lay-skin="switch" lay-text="使用中|封停" lay-filter="switchTest" value="' + data.status + '" checked></a>';
                        } else if (data.status == 4) {
                            var radio2 = '<a href="javascript:updateStatus(' + data.userId + ',' + data.status + ',' + data.enabled + ');"><input class="layui-input swi" type="checkbox" name="status" lay-skin="switch" lay-text="使用中|封停" lay-filter="switchTest" value="' + data.status + '"></a>';
                        }
                        return radio2;
                    }
                },
                {field: "registerDate", title: "注册时间", align: "center"},
                {
                    title: "操作", align: "center", templet: function (data) {
                        return "<div>" +
                            "<a href='javascript:details(" + data.userId + ");' style='color: #2F4056;margin-right: 10px'>查看</a>" +
                            "<a href='javascript:grade(" + data.userId + ");' style='color: #2F4056'>权限</a><br/>" +
                            "<a href='javascript:bianji(" + data.userId + ");' style='color: #2F4056; margin-right: 10px'>编辑</a>" +
                            "<a href='javascript:fengting(\"" + data.userId + "\",\"" + data.account + "\",\"" + data.status + "\");' style='color: #2F4056'>封停</a>" +
                            "</div>";
                    }
                }
            ]
        ]
    });
    /* 表格渲染结束 */

    /* 点击树节点展示不同用户开始 */
    function chooseNode(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        var nodes = zTree.getSelectedNodes();
        var deptName = nodes[0].deptName;
        if (deptName == "所有部门") {
            people.reload({
                url: "/jurisdiction/getJsUser?account=" + '' + "&trueName=" + '' + "&deptName=" + '' + "&registerDate=" + '',
            });
        } else {
            people.reload({
                url: "/jurisdiction/getJsUser?account=" + '' + "&trueName=" + '' + "&deptName=" + deptName + "&registerDate=" + '',
            });
        }
    }

    /* 点击树节点展示不同用户结束 */

    /* 筛选查询开始 */
    form.on('submit(sub)', function (data) {
        var account = $('#account').val();
        var trueName = $('#trueName').val();
        var deptName = $('#deptName').val();
        var registerDate = $('#registerDate').val();
        people.reload({
            url: "/jurisdiction/getJsUser?account=" + account + "&trueName=" + trueName + "&deptName=" + deptName + "&registerDate=" + registerDate,
        });
        return false;
    });
    /* 筛选查询结束 */

    /* 重置开始 */
    form.on('submit(subs)', function (data) {
        people.reload({
            url: "/jurisdiction/getJsUser?account=" + '' + "&trueName=" + '' + "&deptName=" + '' + "&registerDate=" + '',
        });
    });
    /* 重置结束 */

    /* 更新账号状态开始 */
    updateStatus = function updateStatus(userId, status, enabled) {
        if (status == 1) {
            var status1 = 4;
        } else {
            var status1 = 1;
        }

        if (enabled == 1) {
            var enabledd = 2;
        } else {
            var enabledd = 1;
        }
        var unsealDate = new Date();
        unsealDate = getTime(unsealDate);
        var endDate = new Date();
        endDate=getTimes(endDate);
        var json = {
            userId: userId,
            status: status1,
            enabled: enabledd,
            unsealDate:unsealDate,
            endDate:endDate,
            type:2,
            remarks:"紧急封停"
        };
        $.ajax({
            type: "post",
            dataType: "json",
            data: json,
            url: "/jurisdiction/updateStatus",
            success: function (data) {
                location.reload();
            }
        });
    }
    /* 更新账号状态结束 */

    /* 查看详情开始 */
    details = function details(userId) {
        $.ajax({
            type: "post",
            dataType: "json",
            data: {"userId": userId},
            url: "/jurisdiction/getJsUserById",
            success: function (data) {
                chakan(data);
            }
        })
    };

    //查看后弹出赋值
    function chakan(data) {
        var obj;
        layer.open({
            type: 2,
            shode: 0,
            maxmin: true,
            title: "查看用户信息",
            content: "/jurisdiction/jurisdiction-see-uesr.html",
            area: ["1000px", "620px"],
            btn: ["关闭"],
            yes: function (index) {
                layer.close(index);
            }, success: function (layero, index) {
                obj = layero.find('iframe').contents();
                obj.find("#acatarUrl").attr('src', data.data.acatarUrl);
                obj.find("#account").val(data.data.account);
                obj.find("#trueName").val(data.data.trueName);
                obj.find("#sex").val(data.data.sex);
                obj.find("#phone").val(data.data.phone);
                obj.find("#birthDate").val(data.data.birthDate);
                obj.find("#deptName").val(data.data.deptName);
                obj.find("#registerDate").val(data.data.registerDate);
                obj.find("#registerIp").val(data.data.registerIp);
                obj.find("#email").val(data.data.email);
                obj.find("#freestyle").val(data.data.freestyle);
            }
        });
    };
    /* 查看详情结束 */

    /*高级检索开始*/
    $("#retrieval").click(function () {
        var obj;
        layer.open({
            type:2,
            shode:0,
            title:"高级检索",
            content:"/jurisdiction/jurisdiction-people-list-search.html",
            area:["600px","600px"],
            btn:["确定","取消"],
            yes:function (index) {
                var email = obj.find("#email").val();
                var phone = obj.find("#phone").val();
                var idCard = obj.find("#idCard").val();
                var status = obj.find("#status").val();
                var sex = obj.find("#sex").val();
                var enabled = obj.find("#enabled").val();
                people.reload({
                    url: "/jurisdiction/getSearchJsUser?email="+email+"&phone="+phone+"&idCard="+idCard+"&status="+status+"&sex="+sex+"&enabled="+enabled,
                });
                layer.close(index);
            },btn2:function (index) {
                layer.close(index);
            },success:function (layero,index) {
                obj = layero.find('iframe').contents();
            }
        })
    });
    /*高级检索结束*/

    /* 权限开始 */
    grade = function grade(userId) {
        $.ajax({
            type:"post",
            dataType:"json",
            data:{"userId":userId},
            url:"/jurisdiction/getUserSettings",
            success:function (data) {
                quanxian(data);
            }
        })
    };
    function quanxian(data){
        var obj;
        layer.open({
            type:2,
            shode:0,
            maxmin:true,
            title:"权限设置",
            content: "/jurisdiction/jurisdiction-people-list-settings.html",
            area:["900px","500px"],
            success:function (layero,index) {
                obj = layero.find('iframe').contents();
                obj.find("#userId").val(data.data[0].userId);
                obj.find("#trueName").val(data.data[0].trueName);
                obj.find("#remark").val(data.data[0].remark);

                var shu1 = data.data;

                obj.find("#sss").children("input").each(function (i,e) {
                    for(var i =0;i<shu1.length;i++){
                        if($(this).attr('txt')==shu1[i].authorityId){
                            $(this).next("div").click();
                        }
                    }
                });
            }
        });
    };
    /* 权限结束 */

    /* 编辑开始 */
    bianji = function bianji(userId){
        $.ajax({
            type: "post",
            dataType: "json",
            data: {"userId": userId},
            url: "/jurisdiction/getJsUserById",
            success: function (data) {
                Tbianji(data);
            }
        })
    };
    //查看后弹出赋值
    function Tbianji(data) {
        var obj;
        layer.open({
            type:2,
            shode:0,
            maxmin:true,
            title:"编辑用户信息",
            content:"/jurisdiction/jurisdiction-see-uesr-edit.html",
            area:["1000px","620px"],
            btn:["编辑","取消"],
            yes:function (index) {
                var json={
                    acatarUrl:obj.find("#mainImage").val(),
                    userId:obj.find("#userId").val(),
                    account:obj.find("#account").val(),
                    trueName:obj.find("#trueName").val(),
                    sex:obj.find("#sex").val(),
                    phone:obj.find("#phone").val(),
                    birthDate:obj.find("#birthDate").val(),
                    deptId:obj.find("#deptId").val(),
                    email:obj.find("#email").val(),
                    freestyle:obj.find("#freestyle").val()
                };
                $.ajax({
                    type:"post",
                    dataType:"json",
                    data:json,
                    url:"/jurisdiction/updateUser",
                    success:function (data) {
                        layer.close(index);
                    }
                });
                location.reload();
            },
            btn2:function(index){
                layer.close(index);
            },
            success:function (layero,index) {
                obj = layero.find('iframe').contents();
                obj.find("#userId").val(data.data.userId);
                obj.find("#acatarUrl").attr('src',"http://"+data.data.acatarUrl);
                obj.find("#account").val(data.data.account);
                obj.find("#trueName").val(data.data.trueName);
                obj.find("#phone").val(data.data.phone);
                obj.find("#birthDate").val(data.data.birthDate);
                obj.find("#registerDate").val(data.data.registerDate);
                obj.find("#registerIp").val(data.data.registerIp);
                obj.find("#email").val(data.data.email);
                obj.find("#freestyle").val(data.data.freestyle);
                var deptName = '';
                if(data.data.deptId==1){
                    deptName="管理部";
                }else if(data.data.deptId==2){
                    deptName="人事部";
                }else if(data.data.deptId==3){
                    deptName="运营部";
                }else{
                    deptName="教师部";
                }
                var sex = "";
                if(data.data.sex=="男"){
                    sex="男";
                }else{
                    sex="女"
                }
                selectLay(obj,data.data.sex,sex,"#sex");
                selectLay(obj,data.data.deptId,deptName,"#deptId");
            }
        });
    };
    //下拉框矫正
    function selectLay(obj,layValue,value,select) {
        obj.find(select).children().each(function () {
            if ($(this).val() == layValue) {
                var status = 'dd[lay-value=' + layValue + ']';
                obj.find(select).siblings("div.layui-form-select").find('dl').find(status).click();
                $(this).parent().append('<option value="'+layValue+'" selected>' + value + '</option>');
            }
        })
    }
    /* 编辑结束 */

    /* 封停开始 */
    fengting = function fengting(userId,account,status) {
        if(status==4){
            layer.msg("此账号已被封停");
        }else{
            var obj;
            layer.open({
                type:2,
                shode:0,
                maxmin:true,
                title:"账户封停",
                content:"/jurisdiction/jurisdiction-people-list-shutdown.html",
                area:['500px','370px'],
                btn:['确定','取消'],
                yes:function(index){
                    var days = obj.find("#days").val();
                    var reason = obj.find("#reason").val();
                    var startDate = new Date();
                    startDate = getTime(startDate);
                    var endDate = new Date();
                    endDate = getTimes(endDate,days);
                    var status = "4";
                    var enabled = "2";
                    var type = "3";

                    var json = {
                        userId:userId,
                        type:type,
                        reason:reason,
                        startDatee:startDate,
                        endDatee:endDate,
                        days:days,
                        status:status,
                        enabled:enabled
                    };
                    $.ajax({
                        type:"post",
                        dataType:"json",
                        data:json,
                        url:"/jurisdiction/addUserClosure",
                        success:function (data) {
                            location.reload();
                        }
                    });
                },
                btn2:function(index){
                    layer.close(index);
                },
                success:function (layero,index) {
                    obj = layero.find('iframe').contents();
                    obj.find("#account").val(account);
                }
            })
        }
    };
    function getTime(date){
        var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
        var month = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
        var today = date.getDate(); //获取当前日(1-31)
        var hour = date.getHours(); //获取当前小时数(0-23)
        var minute = date.getMinutes(); //获取当前分钟数(0-59)
        var second = date.getSeconds(); //获取当前秒数(0-59)
        var nowTime;
        nowTime = year+'-'+fillZero(month)+'-'+fillZero(today)+' '+fillZero(hour)+':'+fillZero(minute)+':'+fillZero(second);
        return nowTime;
    };
    function getTimes(date,days){
        var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
        var month = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
        var today = date.getDate(); //获取当前日(1-31)
        var hour = date.getHours(); //获取当前小时数(0-23)
        var minute = date.getMinutes(); //获取当前分钟数(0-59)
        var second = date.getSeconds(); //获取当前秒数(0-59)
        days = parseInt(days);
        today = parseInt(today);
        month = parseInt(month);
        year = parseInt(year);
        if(days=="1"){
            today = today+days;
            if(today>32|today>31){
                if(month=1|3|5|7|8|10|12){
                    month+=1;
                }else if(month=4|6|9|11){
                    month+=1;
                }else{
                    month+=1;
                }
            }
        }else if(days=="30"){
            month = month+1;
            if(month>13){
                year=year+1;
            }
        }else if(days=="365"){
            year=year+1;
        }else{
            year=year+100;
        }
        var nowTime;
        nowTime = year+'-'+fillZero(month)+'-'+fillZero(today)+' '+fillZero(hour)+':'+fillZero(minute)+':'+fillZero(second);
        return nowTime;
    };
    function fillZero(str){
        var realNum;
        if(str<10){
            realNum	= '0'+str;
        }else{
            realNum	= str;
        }
        return realNum;
    };
    /* 封停结束 */

    /* 返回开始 */
    goBack = function goBack() {
        //通过页面查找iframe
        parent.$('#Jump').val('首页');
        parent.getQuick();
        return;
    }
    /* 返回结束 */

    /* 刷新开始 */
    Refresh = function Refresh() {
        location.reload();
    };
    /* 刷新结束 */
});